import {
  Cartesian3,
  CesiumWidget,
  Color,
  ColorMaterialProperty,
  GeoJsonDataSource,
  Ion,
  Material,
  Property,
  Viewer,
} from "cesium";

(window as any).CESIUM_BASE_URL = ".";
Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0ZThhOTZlNS05MzgwLTRkNTYtODc1Yy01MTYwMzI3NWUyZmIiLCJpZCI6MjQzNzcsImlhdCI6MTY1NjU1MjkzMH0.XzOOAtPz4ZcVQiQxo5BG5gbeVWtdmTtgwa-5MjCl7-s";

let mapDom = document.createElement("div");
mapDom.id = "app";
mapDom.style.width = "100vw";
mapDom.style.height = "100vh";
document.body.append(mapDom);

let control = document.createElement("div");
control.style.position = "absolute";
control.style.left = "30px";
control.style.top = "30px";
let btn1 = document.createElement("button");
btn1.innerText = "添加行政边界";
btn1.addEventListener("click", handleClick1);
let btn2 = document.createElement("button");
btn2.innerText = "添加行政边界(自定义)";
btn2.addEventListener("click", handleClick2);
let btn3 = document.createElement("button");
btn3.innerText = "添加行政边界(分类)";
btn3.addEventListener("click", handleClick3);
let btn4 = document.createElement("button");
btn4.innerText = "清空";
btn4.addEventListener("click", handleClick4);
control.appendChild(btn1);
control.appendChild(btn2);
control.appendChild(btn3);
control.appendChild(btn4);
document.body.appendChild(control);

let viewer: Viewer;
viewer = new Viewer("app");
viewer.camera.setView({
  destination: Cartesian3.fromDegrees(121, 30, 3000000),
});

let jsonSource;
function handleClick1() {
  let dataSource = viewer.dataSources;
  jsonSource = GeoJsonDataSource.load("./static/json/china.json");
  dataSource.add(jsonSource);
}
function handleClick2() {
  let dataSource = viewer.dataSources;
  jsonSource = GeoJsonDataSource.load("./static/json/china.json", {
    stroke: new Color(1.0, 0, 0, 1.0),
    fill: new Color(1.0, 0, 0, 0.5),
  });
  dataSource.add(jsonSource);
}
function handleClick3() {
  let dataSource = viewer.dataSources;
  let promise = GeoJsonDataSource.load("./static/json/china.json");
  promise.then((ds) => {
    dataSource.add(ds);
    let entities = ds.entities;
    for (let i = 0; i < entities.values.length; i++) {
      let entity = entities.values[i];
      entity.polygon.material = new ColorMaterialProperty(
        Color.fromRandom({
          alpha: 1.0,
        })
      );
    }
  });
}

function handleClick4() {
  let dataSource = viewer.dataSources;
  // dataSource.remove(jsonSource);
  dataSource.removeAll();
}
